# -*- coding: utf-8 -*-
# frontend/utils/state_manager.py
"""
状态管理工具
"""

import streamlit as st
from typing import Any, Dict, Optional
import json
from pathlib import Path

class StateManager:
    """Streamlit状态管理器"""
    
    def __init__(self):
        self.state_file = Path("data/config/app_state.json")
        self.state_file.parent.mkdir(parents=True, exist_ok=True)
    
    def get(self, key: str, default_value: Any = None) -> Any:
        """获取状态值"""
        return st.session_state.get(key, default_value)
    
    def set(self, key: str, value: Any) -> None:
        """设置状态值"""
        st.session_state[key] = value
    
    def update(self, updates: Dict[str, Any]) -> None:
        """批量更新状态"""
        for key, value in updates.items():
            st.session_state[key] = value
    
    def clear(self, key: str) -> None:
        """清除状态值"""
        if key in st.session_state:
            del st.session_state[key]
    
    def save_to_file(self) -> bool:
        """保存状态到文件"""
        try:
            state_data = {
                key: value for key, value in st.session_state.items()
                if isinstance(value, (str, int, float, bool, list, dict))
            }
            
            with open(self.state_file, 'w', encoding='utf-8') as f:
                json.dump(state_data, f, ensure_ascii=False, indent=2)
            
            return True
        except Exception as e:
            st.error(f"保存状态失败: {e}")
            return False
    
    def load_from_file(self) -> bool:
        """从文件加载状态"""
        try:
            if self.state_file.exists():
                with open(self.state_file, 'r', encoding='utf-8') as f:
                    state_data = json.load(f)
                
                for key, value in state_data.items():
                    if key not in st.session_state:
                        st.session_state[key] = value
                return True
        except Exception as e:
            st.error(f"加载状态失败: {e}")
            return False
    
    def reset_all(self) -> None:
        """重置所有状态"""
        for key in list(st.session_state.keys()):
            del st.session_state[key]